package fr.mma.achievement.controller;

import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

import fr.mma.achievement.dao.AchievementDao;
import fr.mma.achievement.exception.NoSuchAchievementException;
import fr.mma.achievement.model.persistence.Achievement;
import fr.mma.livraison.model.dto.LivraisonApplicationDTO;

public class AchievementsManager {
	
	private static AchievementDao dao = new AchievementDao();
	
	public static void update(final LivraisonApplicationDTO livraisonApplication) {
		List<Achievement> achievementList = dao.getAll();
		CollectionUtils.filter(achievementList, new Predicate() {
			@Override
			public boolean evaluate(Object arg0) {
				Achievement achievement = (Achievement)arg0;
				boolean auBonDev = achievement.getDeveloppeur().getName().equals(livraisonApplication.getDeveloppeur().getTrigram());
				return auBonDev && !achievement.isFinish();
			}
		});
		update(achievementList, livraisonApplication);
		for (Achievement achievement : achievementList) {
			dao.save(achievement);
		}
	}
	
	public static void update(Collection<Achievement> achievements, LivraisonApplicationDTO livraisonApplication){
		for (Achievement achievement : achievements) {
			try {
				AchievementControllerFactory.build(achievement.getType()).update(achievement, livraisonApplication);
			} catch (NoSuchAchievementException e) {
				e.printStackTrace();
			}
		}
	}
}
